import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { UserService } from 'src/app/service/user.service';
import { YearawardService } from '../../yearaward.service';
import { BaseService } from 'src/app/service/base.service';
import { UtilsService } from 'src/app/service/utils.service';
import { NO_QUALIFICATION_FIELD_VALUE } from 'src/constants';
import type { Subscription } from 'rxjs';

@Component({
  selector: 'app-xinxiu-promotion',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss'],
})
export class XinxiuPromotionComponent implements OnInit {
  @Input() timeConfig: any[] = [];
  @ViewChild('main', { static: false }) main: ElementRef;
  /* ___ _ ___ */
  public deployUrl: string; /* 资源地址前缀 */
  private reshing: Subscription = null; /* 订阅刷新 */
  private observer: IntersectionObserver; /* 实例 Inersction Observer */
  /* ___ _ ___ */
  public isPC = false; /* 是否pc */
  public isAndroid = false; /* 是否安卓 */
  public onRefrash = false; /* 刷新中 */
  public pageSize = 30; /* 每页条数 */
  public anchorShow = false; /* 主播信息显示 */
  /* ___ _ ___ */
  public loading = false;
  public status: 1 | 2 | 3 = undefined; /* 榜单状态 */
  public stageId: number;
  public top3List: EndYear.IAnchor[] = []; /* TOP3 */
  public othersList: EndYear.IAnchor[] = []; /* OTHERS */
  public dangersList: EndYear.IAnchor[] = []; /* DANGERS */
  public eliminationsList: EndYear.IAnchor[] = []; /* ELIMINATIONS */
  public currentAnchorInfo: EndYear.ICurrentAnchor = {
    nickname: '',
    avatarUrl: '',
    score: 0,
    rankDesc: '-',
    rank: 0,
    isMysteryMan: false,
    liveStatus: false,
  }; /* 当前主播信息 */

  constructor(
    private userService: UserService,
    private yearawardService: YearawardService,
    public baseService: BaseService,
    private utilsService: UtilsService
  ) {}

  ngOnInit(): void {
    // 获取
    this.deployUrl = this.userService.getDeployUrl();
    this.isPC = this.userService.getIsPc();
    this.isAndroid = this.utilsService.getBrowserVersion();

    this.init();
    // 组件刷新通信
    this.reshing = this.utilsService.MsgSub.subscribe(() => {
      this.init();
    });
  }

  init() {
    //获取当前榜单
    const [{ status, stageId }] = this.baseService.useStatusWithTargetTypes(
      this.timeConfig,
      29
    );
    this.stageId = stageId;
    this.status = status;
    console.log('新秀榜 晋级赛=>', status, stageId);
    // 请求数据
    this.getList();
    this.getCurrentAnchor();
  }

  ngOnDestroy(): void {
    /* 取消订阅 */
    if (this.reshing) this.reshing.unsubscribe();
    /* 清除 Intersection Observer */
    if (this.observer) this.observer.unobserve(this.main.nativeElement);
  }

  /**
   * @description: 初始化请求列表
   */
  // 获取榜单
  getList() {
    this.yearawardService.getActivityRanking(
      (res: any) => {
        if (res.code == 200) {
          const list = res.data.list;
          const len = 3 - list.length;
          if (len > 0) {
            for (let i = 0; i < len; i++) {
              list.push({
                avatarUrl: '',
                score: 0,
                rank: i + 1,
                nickname: '虚位以待',
                rankDesc: '-',
              });
            }
          }
          if (this.status === 3) {
            // 已结束
            this.top3List = list.slice(0, 3);
            this.othersList = list.slice(3, 10);
            this.dangersList = [];
            this.eliminationsList = list.slice(10);
          } else {
            // 进行中
            this.top3List = list.slice(0, 3);
            this.othersList = list.slice(3, 10);
            this.dangersList = list.slice(10);
            this.eliminationsList = [];
          }
        }
      },
      this.stageId,
      this.pageSize,
      (err: any) => {}
    );
  }
  /**
   * @description: 获取更多...
   */
  async getMore() {
    if (this.onRefrash) return;
    // 获取最小页数
    this.pageSize = Math.min(this.pageSize + 20, 100);
    // 重新请求
    this.getList();
    this.getCurrentAnchor();
  }

  /**
   * @description: 获取当前主播
   */
  getCurrentAnchor() {
    this.loading = true;
    this.yearawardService.getCurrentAnchorRanking(
      ({ code, data, message }) => {
        if (code === 200) {
          const { rank, rankDesc } = this.baseService.useCurrentInfo(data);
          this.currentAnchorInfo = {
            ...data,
            rank,
            rankDesc,
          };
        } else {
          this.baseService.showToast(message, 1500);
        }
        this.loading = false;
      },
      this.baseService.getCurrentId(),
      this.stageId,
      () => {}
    );
  }

  /**
   * @description: 跳转直播间
   */
  public goToRoom(
    item: Record<string, any>,
    type: 'anchor' | 'user' = 'anchor'
  ) {
    item.uid = item.uid ?? item.anchorUid;
    if (
      (type === 'anchor' && !item.uid) ||
      (type === 'user' && !item.userUid)
    ) {
      return;
    }
    const obj = { ...item };
    if (type === 'anchor') {
      obj.isMysteryMan = false;
    }
    obj.livImage = item.avatarUrl;
    this.utilsService.gotoRoom(obj, type);
  }

  ngAfterViewInit(): void {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.
    this.observer = this.baseService.useIntersectionObserver(
      this.main.nativeElement,
      (visibility) => {
        this.anchorShow = visibility;
      }
    );
  }
}
